package com.huiben.app.cartoonbooks.app;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huiben.app.cartoonbooks.R;
import com.huiben.app.cartoonbooks.base.BaseActivity;
import com.huiben.app.cartoonbooks.content.test.TestActivity;
import com.huiben.app.cartoonbooks.listener.onPlayListener;
import com.huiben.app.cartoonbooks.service.PlayerService;
import com.huiben.app.cartoonbooks.utils.ImageLoader;
import com.huiben.app.cartoonbooks.utils.SharedUtils;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 *
 * 1 实现边播放边下载 ,
 * 2 实现保存播放的语言
 */
public class FrameActivity extends BaseActivity<FramePresenter, FrameModel> implements FrameContract.View ,ViewPager.OnPageChangeListener  , View.OnClickListener{


    private static final String TAG = FrameActivity.class.getSimpleName();
    @Bind(R.id.viewpager)
    ViewPager viewpager;
    @Bind(R.id.re_toptile)
    RelativeLayout reToptile;
    @Bind(R.id.tv_shuangyu)
    TextView tvShuangyu;
    @Bind(R.id.tv_english)
    TextView tvEnglish;
    @Bind(R.id.tv_count)
    TextView tvcount;
    @Bind(R.id.iv_top)
    ImageView ivTop;
    @Bind(R.id.iv_next)
    ImageView ivNext;
    @Bind(R.id.re_buttontile)
    RelativeLayout reButtontile;

    int tabLayoutHeight;
    @Bind(R.id.tv_title)
    TextView tvTitle;

    // 显示 和 隐藏标题
    private boolean flage = false;
     private  Timer     DISMISS_CONTROL_VIEW_TIMER;
  private    DismissControlViewTimerTask      mDismissControlViewTimerTask ;


    ArrayList<FrameBean.DataBean> listPlay = new ArrayList<>();
//   当前播放的语言状态
     private  int  statelanguage=11;
    private  int LanguageEnglish=12;
     private  int LanguageShangyu=13;
    // 多段音频中的 位置
    private  int  position =0;
     private  String id;

    private List<PhotoView> mImageViews = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.test_play_view;
    }

    @Override
    protected void initView() {


    }


    @Override
    protected void initPresenter() {
        Log.e(TAG, "initPresenter: ");
        presenter.setVM(this, model);
        presenter.getOneNewsDataRequest(this,"154");
        ;
    }




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
         id = getIntent().getStringExtra("id");
        //初始化状态
//        setUiWitStateAndScreen(CURRENT_STATE_PLAYING);
        List<CacheEntity<Object>> all = CacheManager.INSTANCE.getAll();
        Log.e(TAG, "onCreate: all.size()"+all.size() );
                 for (CacheEntity<Object> cacheEntity : all) {
                     System.out.println(cacheEntity);
                     StringBuilder sb = new StringBuilder();
                     sb.append("共" + all.size() + "条缓存：").append("\n\n");
                     for (int i = 0; i < all.size(); i++) {
                         CacheEntity<Object> cacheEntitys = all.get(i);
                         sb.append("第" + (i + 1) + "条缓存：").append("\n").append(cacheEntitys).append("\n\n");
                     }

                     Log.e(TAG, "所有缓存显示: "+sb.toString());
                 }
        // 设置 上下标题透明度
        reToptile.setAlpha(0.5f);
        reButtontile.setAlpha(0.5f);

        reButtontile.measure(0, 0);
        tabLayoutHeight = reButtontile.getMeasuredHeight();

        ivNext.setOnClickListener(this);

        ivTop.setOnClickListener( this);
        reButtontile.setOnClickListener(this);


         viewpager.setOnPageChangeListener( this);
        startDismissControlViewTimer();
    }


    public void startDismissControlViewTimer() {
        cancelDismissControlViewTimer();
             DISMISS_CONTROL_VIEW_TIMER = new Timer();
              mDismissControlViewTimerTask = new DismissControlViewTimerTask();
        DISMISS_CONTROL_VIEW_TIMER.schedule(mDismissControlViewTimerTask, 5000  );
    }

    public void cancelDismissControlViewTimer() {
        if (DISMISS_CONTROL_VIEW_TIMER != null) {
            DISMISS_CONTROL_VIEW_TIMER.cancel();
        }
        if (mDismissControlViewTimerTask != null) {
            mDismissControlViewTimerTask.cancel();
        }

    }
//

    // 设置数据状态
    @Override
    public void ShowPalyData(FrameBean list) {
        listPlay.clear();
        listPlay.addAll(list.getData());
        initData();
//        tvTitle.setText(list.get(0).get);
            // 获取到数据的时候进行播放和缓存. 第一次 ,  后面进行优化   还要判断 之后 的没有网络之类 ,  先放在这边进行测试



        if (MyApp.getPlayerService() == null) {
            bindService(new Intent(getApplicationContext(), PlayerService.class), MyApp.getmConnection(), BIND_AUTO_CREATE);
        }
        //设置播放监听器
        MyApp.getPlayerService().setPlayListener(mOnPlayListener);

        statelanguage=LanguageShangyu;

          tvShuangyu.setOnClickListener(this);
          tvEnglish.setOnClickListener(this);

        // 获取上一次选组的 语言
        int language = SharedUtils.getInt("language"+id, 0);


           if (language==LanguageShangyu){

                tvShuangyu.callOnClick();


           }else  if(language== LanguageEnglish){
               tvEnglish.callOnClick();
           } else{
               tvShuangyu.callOnClick();
           }


    }

    /**
     *  选择播放 是双语还是英语
     * @param x
     */
     private  void  PlayStateMusic(int x){
         Log.e(TAG, "PlayStateMusic: " );
         if (MyApp.getPlayerService() != null) {
             MyApp.getPlayerService().stop();
             FrameBean.DataBean frameBena = listPlay.get(viewpager.getCurrentItem());
             if (x == LanguageEnglish) {

                 if (frameBena.getAudio() != null){

                     position =0;
                     String audiopath = frameBena.getAudio().get(1).getAudiopath();
                 String s = frameBena.getAudio().get(1).getAudioname().get(0);
                 MyApp.getPlayerService().playInInternet(audiopath+s);
                 }
             } else {
                 if (frameBena.getAudio() != null)

                 {
                     String audiopath = frameBena.getAudio().get(0).getAudiopath();
                     position =0;
                     String s = frameBena.getAudio().get(0).getAudioname().get(0);
                     MyApp.getPlayerService().playInInternet(audiopath+s);
                 }


             }
         }

     }

    private void initData() {
        Log.e(TAG, "initData: listPlay" + listPlay.size());
        mImageViews.clear();
        for (FrameBean.DataBean bean : listPlay) {
            PhotoView imageView = new PhotoView(getApplicationContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);


//            imageView.setImageResource(bean.getImg());

//            new GlideImageLoader().onDisplayImage(this, imageView, bean.getImg());

            ImageLoader.newInstance().displayImage(this,bean.getImg(),imageView);
            mImageViews.add(imageView);
        }

        PalyAdapter palyAdapter = new PalyAdapter();

        viewpager.setAdapter(palyAdapter);








    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        // 滑动的时候调用
        Log.e(TAG, "onPageSelected: mImageViews.size())"+mImageViews.size());


        tvcount.setText(position+1+"/"+mImageViews.size());

        PlayStateMusic (statelanguage);


    }

    @Override
    public void onPageScrollStateChanged(int state) {


    }

    @Override
    public void onClick(View v) {
         switch (v.getId()){
             // 下一选择
             case  R.id.iv_next:
//                 setUiWitStateAndScreen(CURRENT_STATE_PREPARING);
                 int currentItem = viewpager.getCurrentItem();
                 viewpager.setCurrentItem(currentItem+1);

                 break;
             // 上一选择
             case  R.id.iv_top:
//                 setUiWitStateAndScreen(CURRENT_STATE_PREPARING);
                 int postion = viewpager.getCurrentItem();
                 viewpager.setCurrentItem(postion-1);

                 break;
             case R.id.tv_english:
                 tvEnglish.setEnabled(false);
                 tvShuangyu.setEnabled(true);
                 tvEnglish.setTextColor( FrameActivity.this.getResources().getColor(R.color.them_blue));
                 tvEnglish.setBackgroundResource(R.drawable.tv_languaue_blue);
                 tvShuangyu.setTextColor( FrameActivity.this.getResources().getColor(R.color.white));
                 tvShuangyu.setBackgroundResource(R.drawable.tv_languaue_white);
                 statelanguage=LanguageEnglish;
                 PlayStateMusic (statelanguage);

                 SharedUtils.putInt("language"+id,LanguageEnglish );
                 break;
             case R.id.tv_shuangyu:

                 tvShuangyu.setEnabled(false);
                 tvEnglish.setEnabled(true);
                 statelanguage=LanguageShangyu;
                 tvEnglish.setTextColor( FrameActivity.this.getResources().getColor(R.color.white));

                 tvEnglish.setBackgroundResource(R.drawable.tv_languaue_white);
                 tvShuangyu.setTextColor( FrameActivity.this.getResources().getColor(R.color.them_blue));
                 tvShuangyu.setBackgroundResource(R.drawable.tv_languaue_blue);
                 PlayStateMusic (statelanguage);
                 SharedUtils.putInt("language"+id,LanguageShangyu );
                 break;

                    // 屏幕
             case R.id.re_buttontile:
//                 setUiWitStateAndScreen(CURRENT_STATE_PREPARING);
                  break;

         }
    }




    private class PalyAdapter extends PagerAdapter {
        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            container.addView(mImageViews.get(position));

//            // 点击图片显示和 隐藏
//            mImageViews.get(position).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//
//                    onClickUiToggle();
//                }
//            });
            // 点击图片进行隐藏
            mImageViews.get(position).setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                @Override
                public void onPhotoTap(View view, float v, float v1) {
                    hideOrShowToolbar();
//                    hideOrShowStatusBar();
                }
            });
            tvcount.setText(position+"/"+mImageViews.size());
            return mImageViews.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position,
                                Object object) {

            container.removeView(mImageViews.get(position));
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public int getCount() {
            return mImageViews.size();
        }


//        //显示和隐藏动画效果
//
//        private void startAnimation(boolean showOrHide, final View view) {
//
//
//            final ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
//            ValueAnimator valueAnimator;
//            ObjectAnimator alpha;
//            if (!showOrHide) {
//                // 隐藏
//                Log.e(TAG, "startAnimation: " + showOrHide);
//                valueAnimator = ValueAnimator.ofInt(tabLayoutHeight, 0);
//                alpha = ObjectAnimator.ofFloat(view, "alpha", 1, 0);
//            } else {
//                //显示
//                valueAnimator = ValueAnimator.ofInt(0, tabLayoutHeight);
//                alpha = ObjectAnimator.ofFloat(view, "alpha", 0, 1);
//            }
//            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//                @Override
//                public void onAnimationUpdate(ValueAnimator valueAnimator) {
//                    layoutParams.height = (int) valueAnimator.getAnimatedValue();
//                    view.setLayoutParams(layoutParams);
//                }
//            });
//            AnimatorSet animatorSet = new AnimatorSet();
//            animatorSet.setDuration(500);
//            animatorSet.playTogether(valueAnimator, alpha);
//            animatorSet.start();
//        }


    }

    protected void hideOrShowToolbar() {
        reToptile .animate()
                .alpha(mIsToolBarHidden ? 0.5f : 0.0f)
                .setInterpolator(new DecelerateInterpolator(2))
                .start();
        reButtontile.animate()
                .alpha(mIsToolBarHidden ? 0.5f : 0.0f)
                .setInterpolator(new DecelerateInterpolator(2))
                .start();
        mIsToolBarHidden = !mIsToolBarHidden;
    }
 private   boolean mIsToolBarHidden=false;

//

        // 定时器 5秒自动关闭
    public class DismissControlViewTimerTask extends TimerTask {

        @Override
        public void run() {
                         if (!mIsToolBarHidden) {

                             runOnUiThread(new Runnable() {
                                 @Override
                                 public void run() {
                                     mIsToolBarHidden = true;
//

                                 }
                             });
                         }
            }
        }

        //播放事件回调
    private onPlayListener mOnPlayListener = new onPlayListener() {
        @Override
        public void onCache(float percent) {

        }

        @Override
        public void onPlay(long playPosition) {

        }

        @Override
        public void onStart(long duration) {
            Log.e(TAG, "onStart: 开始播放" );
        }

        @Override
        public void onContinuePlay() {
            Log.e(TAG, "onPause:继续播放 " );
        }

        @Override
        public void onPause() {
            Log.e(TAG, "onPause:暂停 " );
        }

        @Override
        public void onStop() {
            Log.e(TAG, "onStop: " );
        }

        @Override
        public void onSuccess() {
            int currentItem = viewpager.getCurrentItem();
            FrameBean.DataBean frameBena = listPlay.get(currentItem);
            //当前图片只有一段录音
            //当前是yi

            Log.e(TAG, "onSuccess: " );

            int language = SharedUtils.getInt("language"+id, 0);
             if (language!=LanguageEnglish){
            String Baseaudiopath = frameBena.getAudio().get(1).getAudiopath();
         String  shuangyu=    frameBena.getAudio().get(0).getLanguage();
                // 当前是双语
           if (shuangyu.endsWith("0")) {
               Log.e(TAG, "onSuccess: 双语");
               // 多段音频
               if (frameBena.getAudio().get(0).getAudioname().size() > 1) {
                   //  判断当前是播放是多段中的第几个音频

                   position = position + 1;
                   //必须保证当前的位置不能超过音频数据的集合
                   if (position < frameBena.getAudio().get(0).getAudioname().size()) {
                       String s = frameBena.getAudio().get(0).getAudioname().get(position);
                       MyApp.getPlayerService().playInInternet(Baseaudiopath + s);
                       Log.e(TAG, "onSuccess:  双语,  多个音频");
                   } else {
                       viewpager.setCurrentItem(currentItem + 1);
                   }


               } else {
                   Log.e(TAG, "onSuccess:  双语,  只有一个音频");
                   viewpager.setCurrentItem(currentItem + 1);
               }
           }

               // 英语
           }else{
               Log.e(TAG, "onSuccess: 英语" );
               String BaseEnglishaudiopath = frameBena.getAudio().get(1).getAudiopath();
                    //当前文件有多段录音文件
                 if (frameBena.getAudio().get(1).getAudioname().size() >1){

                     //  判断当前是播放是多段中的第几个音频
                     position=    position +1;
                     //必须保证当前的位置不能超过音频数据的集合
                      if (position <frameBena.getAudio().get(1).getAudioname().size() ){
                          String s = frameBena.getAudio().get(1).getAudioname().get(position);
                          MyApp.getPlayerService().playInInternet(BaseEnglishaudiopath+s);
                          Log.e(TAG, "onSuccess:  英语,  多个音频" );
                      }else{
                          viewpager.setCurrentItem(currentItem+1);
                      }

//

                 }else {
                     Log.e(TAG, "onSuccess:  英语,  只有一个音频" );
                     viewpager.setCurrentItem(currentItem+1);
                 }


           }




        }

        @Override
        public void onFailure() {
            Log.e(TAG, "onSuccess:  播放失败" );
        }
    };

}
